package com.ay.selfservicemachine.utils;

import android.Manifest;
import android.app.NotificationManager;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;

import androidx.core.content.ContextCompat;

import java.util.ArrayList;
import java.util.List;

/**
 * 文件权限处理类
 */
public class HQWPermissionUtil {


    /****************************************普通权限处理*************************************/

    /**
     * @param InputPermissions 需要处理的安卓动权
     *                         安卓动权修改如下:
     * @旧:(文件读写)||安卓10- READ_EXTERNAL_STORAGE
     * WRITE_EXTERNAL_STORAGE
     * @新:(文件读写)||安卓10&+ READ_EXTERNAL_STORAGE
     * @旧:(文件读写)||安卓13- READ_EXTERNAL_STORAGE
     * @新:(文件读写)||安卓13&+ READ_MEDIA_IMAGES
     * READ_MEDIA_AUDIO
     * READ_MEDIA_VIDEO
     * @新:(蓝牙权限)||安卓12&+ BLUETOOTH_CONNECT
     * BLUETOOTH_SCAN
     * BLUETOOTH_ADVERTISE
     * @新:(WIFI)||安卓13&+ NEARBY_WIFI_DEVICES
     */
    public static String[] PermissionDispose(String[] InputPermissions) {//安卓13动权处理
        List<String> resultPermissions = new ArrayList<>();
        boolean isAtLeastAndroid13 = Build.VERSION.SDK_INT >= 33;
        boolean isAndroid12To12L = Build.VERSION.SDK_INT >= 31 && Build.VERSION.SDK_INT < 33;
        boolean isAndroid11 = Build.VERSION.SDK_INT == 30;

        for (int i = 0; i < InputPermissions.length; i++) {
            String permission = InputPermissions[i];

            // 统一用 equals 比较字符串，避免引用比较导致的判断错误
            if (isAtLeastAndroid13) {
                // Android 13+ 不支持 READ/WRITE_EXTERNAL_STORAGE，改为 READ_MEDIA_*
                if (Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(permission)
                        || Manifest.permission.READ_EXTERNAL_STORAGE.equals(permission)) {
                    addIfAbsent(resultPermissions, Manifest.permission.READ_MEDIA_IMAGES);
                    addIfAbsent(resultPermissions, Manifest.permission.READ_MEDIA_VIDEO);
                    addIfAbsent(resultPermissions, Manifest.permission.READ_MEDIA_AUDIO);
                } else {
                    addIfAbsent(resultPermissions, permission);
                }
            } else if (isAndroid12To12L || isAndroid11) {
                // Android 11-12L：WRITE_EXTERNAL_STORAGE 基本无效，保留 READ_EXTERNAL_STORAGE 以保证读取能力
                if (Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(permission)) {
                    addIfAbsent(resultPermissions, Manifest.permission.READ_EXTERNAL_STORAGE);
                } else if (Manifest.permission.READ_MEDIA_AUDIO.equals(permission)
                        || Manifest.permission.READ_MEDIA_IMAGES.equals(permission)
                        || Manifest.permission.READ_MEDIA_VIDEO.equals(permission)) {
                    // 低于 33 不存在 READ_MEDIA_*，忽略
                } else {
                    addIfAbsent(resultPermissions, permission);
                }
            } else {
                // Android 10 及以下：不请求 WRITE_EXTERNAL_STORAGE，统一使用 READ_EXTERNAL_STORAGE；忽略不存在的 READ_MEDIA_*
                if (Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(permission)) {
                    addIfAbsent(resultPermissions, Manifest.permission.READ_EXTERNAL_STORAGE);
                } else if (Manifest.permission.READ_MEDIA_AUDIO.equals(permission)
                        || Manifest.permission.READ_MEDIA_IMAGES.equals(permission)
                        || Manifest.permission.READ_MEDIA_VIDEO.equals(permission)) {
                    // 忽略不存在的新权限
                } else {
                    addIfAbsent(resultPermissions, permission);
                }
            }
        }

        String[] OutPermissions = new String[resultPermissions.size()];
        for (int i = 0; i < resultPermissions.size(); i++) {
            OutPermissions[i] = resultPermissions.get(i);
        }
        return OutPermissions;
    }

    private static void addIfAbsent(List<String> list, String value) {
        if (!list.contains(value)) {
            list.add(value);
        }
    }


    /**
     * 判断普通权限是否授权
     */
    public static boolean havePermissions(Context context,String[] permissions) {
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(context, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }


    /****************************************特殊权限处理*************************************/

    /**
     * 特殊权限动作
     */
    public static Intent permissionSpecialAction(Context context, String permission) {
        Intent intent = new Intent();
        switch (permission) {
            case Manifest.permission.SYSTEM_ALERT_WINDOW:
                intent.setAction(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                intent.setData(Uri.parse("package:" + context.getPackageName()));
                return intent;
            case SYSTEM_POSITION_SWITCH:
                intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                return intent;
            case SYSTEM_APK_INSTALL:
                intent.setAction(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                intent.setData(Uri.parse("package:" + context.getPackageName()));
                intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                return intent;
            case SYSTEM_NOTIFICATION_SWITCH:
                intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
                intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName());
                return intent;
            case SYSTEM_BlueTooth_SWITCH:
                intent.setAction(Settings.ACTION_BLUETOOTH_SETTINGS);
                return intent;
            default:
                return intent;
        }
    }

    /**
     * 判断特殊权限是否授权
     */
    public static boolean havePermissionSpecial(Context context, String permission) {
        switch (permission) {
            case Manifest.permission.SYSTEM_ALERT_WINDOW://请求悬浮窗权限
                return Settings.canDrawOverlays(context);//悬浮窗是否打开
            case SYSTEM_POSITION_SWITCH:
                return isLocationServiceEnabled(context);
            case SYSTEM_APK_INSTALL:
                return isApkInstallEnabled(context);
            case SYSTEM_NOTIFICATION_SWITCH:
                return isOpenNotificationSwitch(context);
            case SYSTEM_BlueTooth_SWITCH:
                return isBlueToothSwitchEnabled(context);
            default:
                return false;
        }
    }


    /****************************************特殊权限创造*************************************/

    public static final String SYSTEM_POSITION_SWITCH = "System.position.switch";//自定义权限获取 系统定位开关
    public static final String SYSTEM_APK_INSTALL = "System.installs";//安装所有应用
    public static final String SYSTEM_NOTIFICATION_SWITCH = "System.notification.switch";//通知权限
    public static final String SYSTEM_DEVELOPER_OPTIONS_SWITCH = "System.oeveloper_options.switch";//开发者选项开关

    public static final String SYSTEM_BlueTooth_SWITCH = "System.bluetooth.switch";//蓝牙选项开关

    /**
     * 判断位置是否已打开
     *
     * @param context 上下文对象
     * @return 位置是否已打开
     */
    public static boolean isLocationEnabled(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        return isGpsEnabled || isNetworkEnabled;
    }

    /**
     * 判断位置服务是否已开启
     *
     * @param context 上下文对象
     * @return 位置服务是否已开启
     */
    public static boolean isLocationServiceEnabled(Context context) {
        int locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE, Settings.Secure.LOCATION_MODE_OFF);
        return locationMode != Settings.Secure.LOCATION_MODE_OFF;
    }

    /**
     * 判断通知开关是否打开
     *
     * @param context 上下文对象
     * @return 通知开关是否打开
     */
    public static boolean isOpenNotificationSwitch(Context context) {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        return notificationManager.areNotificationsEnabled();
    }

    /**
     * 是否拥有应用apk的安装权限
     */
    public static boolean isApkInstallEnabled(Context context) {
        boolean isOpen = false;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            isOpen = context.getPackageManager().canRequestPackageInstalls();
        }
        return isOpen;
    }

    /**
     * 蓝牙是否打开
     */
    public static boolean isBlueToothSwitchEnabled(Context context) {//蓝牙开关是否打开
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter==null){//设备不支持蓝牙
            return false;
        }else {
            return bluetoothAdapter.isEnabled();
        }
    }

    /**
     * 开发者选项是否打开
     */
    public static boolean areDeveloperOptionsEnabled(Context context) {
//        ContentResolver resolver = context.getContentResolver();
//        return Settings.Global.getInt(resolver, Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0) != 0;
        return  false;
    }


}
